<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    div {
        width: 200px;
        height: 200px;
        background-color: yellow;
        position: absolute;
        top: 0;
        left: 0;
    }
</style>
<script>

</script>
<body>
<div id="drag">Drag</div>
<script>

    //获取div 改变this的指向 设置点击事件
    function Rome(id) {
        this.oDiv = document.getElementById(id)
        var _this = this;
        this.oDiv.onmousedown = function (ev) {
//            console.log(1)
            _this.downs(ev);
            return false;
        };
    };

    Rome.prototype.downs = function (ev) {
//        console.log(1)
        var oEvent = ev || event;//兼容
        var _this = this;//改变this指向
        this.x = oEvent.clientX - this.oDiv.offsetLeft;
        this.y = oEvent.clientY - this.oDiv.offsetTop;
//        console.log(this.x)
        document.onmousemove = function (ev) {
            _this.moves(ev);
        };
        document.onmouseup = function () {
            _this.ups();
        };
    };

    Rome.prototype.moves = function (ev) {
        var oEvent = ev || event;
        var outX = oEvent.clientX - this.x;
        var outY = oEvent.clientY - this.y;
        console.log(oEvent.clientX);
        if (outX<=0) {
            outX=0;
        }else if(outX>document.documentElement.clientWidth-this.oDiv.offsetWidth){
            outX=document.documentElement.clientWidth-this.oDiv.offsetWidth;
        };
        if (outY<=0) {
            outY=0;
        }else if(outY>document.documentElement.clientHeight-this.oDiv.offsetHeight){
            outY=document.documentElement.clientHeight-this.oDiv.offsetHeight;
        };
        this.oDiv.style.left=outX+'px';
        this.oDiv.style.top=outY+'px';

    };
    Rome.prototype.ups = function (ev) {
        document.onmousemove = null;
        document.onmousput = null;
    };
    var dg=new Rome('drag')
</script>
</body>
</html>